import gettext

# 初始化国际化支持
_ = gettext.gettext

# 示例：将界面文本提取为可翻译的字符串
LABEL_TEXT = _("请输入密码：")
BUTTON_TEXT = _("确认")


import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from app.gui import components
from app.processors import (
    cmd_processor,
    csv_processor,
    iic_processor,
    pps_processor,
    spi_processor
)
from app.utils.crypto_utils import decrypt_and_validate_license_code
from creat_license import encrypt_license_info


# gui/main_window.py
from gui import debug_print


class MainWindow(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("硬件分析工具 v8.1")
        self.geometry("1400x900")

        self._preload_core_styles()
        self._setup_ui()

    def _preload_core_styles(self):
        """安全预加载核心样式"""
        colors = [
            "#FF9800", "#4CAF50", "#2196F3",
            "#9C27B0", "#009688", "#795548",
            "#607D8B", "#E91E63"
        ]
        for color in colors:
            components.create_modern_button(None, "", None, color)

    def _setup_ui(self):
        # 主容器
        main_frame = ttk.Frame(self)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)

        # 工具栏
        toolbar = ttk.Frame(main_frame)
        toolbar.pack(side=tk.TOP, fill=tk.X)

        # 功能按钮组
        actions = [
            ("📁 CSV处理", "#FF9800", self._process_csv),
            ("🔍 IIC解析", "#4CAF50", self._parse_iic),
            ("📡 SPI解析", "#2196F3", self._parse_spi),
            ("🔄 PPS转换", "#9C27B0", self._convert_pps),
            ("⚡ 指令提取", "#009688", self._extract_cmd)
        ]

        for text, color, handler in actions:
            btn = components.create_unified_button(
                toolbar,
                text,
                handler,
                color
            )
            btn.pack(side=tk.LEFT, padx=5)

        # 添加授权管理按钮，统一样式
        license_button = components.create_unified_button(
            toolbar,
            text="授权管理",
            command=self._prompt_password_for_license,
            color="#607D8B"  # 使用统一的背景颜色
        )
        license_button.pack(side=tk.LEFT, padx=5)

        # 输出面板
        frame, text_area = components.create_output_panel(main_frame)
        frame.pack(fill=tk.BOTH, expand=True)
        self.output = text_area

    # 临时方法实现（示例）
    def _process_csv(self):
        self.output.insert(tk.END, "CSV处理中...\n")

    def _parse_iic(self):
        self.output.insert(tk.END, "IIC解析中...\n")

    def _parse_spi(self):
        self.output.insert(tk.END, "IIC解析中...\n")

    def _convert_pps(self):
        self.output.insert(tk.END, "IIC解析中...\n")

    def _extract_cmd(self):
        self.output.insert(tk.END, "IIC解析中...\n")

    def _open_settings(self):
        """临时空实现"""
        debug_print("设置功能暂未实现")

    def _show_stats(self):
        """临时空实现"""
        debug_print("统计功能暂未实现")

    def _show_help(self):
        """临时空实现"""
        debug_print("帮助功能暂未实现")

    def _create_action_buttons(self, parent):
        """主操作按钮组"""
        action_frame = ttk.LabelFrame(parent, text="核心功能", padding=10)
        action_frame.pack(side=tk.LEFT, padx=10)

        buttons = [
            ("📁 CSV批处理", "#FF9800", csv_processor.select_files_and_process),
            ("🔍 IIC解析", "#4CAF50", iic_processor.extract_iic_data),
            ("📡 SPI解析", "#2196F3", spi_processor.extract_spi),
            ("🔄 PPS转换", "#9C27B0", pps_processor.convert_gui),
            ("⚡ 指令提取", "#009688", cmd_processor.extract_gui)
        ]

        for text, color, handler in buttons:
            # 修复闭包绑定问题，显式绑定当前变量
            btn = components.create_modern_button(
                action_frame,
                text=text,
                command=lambda h=handler: h(self.output),  # ✅ 显式绑定
                bg_color=color
            )
            btn.pack(side=tk.LEFT, padx=5, pady=2)

    def _create_utility_buttons(self, parent):
        """工具按钮组"""
        util_frame = ttk.Frame(parent)
        util_frame.pack(side=tk.RIGHT, padx=10)

        util_buttons = [
            ("⚙️ 设置", "#795548", self._open_settings),
            ("📊 统计", "#607D8B", self._show_stats),
            ("❓ 帮助", "#E91E63", self._show_help)
        ]

        for text, color, handler in util_buttons:
            btn = components.create_modern_button(
                util_frame,
                text=text,
                command=handler,
                bg_color=color
            )
            btn.pack(side=tk.LEFT, padx=5, pady=2)

        # 添加分隔线
        ttk.Separator(util_frame, orient=tk.VERTICAL).pack(side=tk.LEFT, padx=10, fill=tk.Y)

    def _prompt_password_for_license(self):
        """提示用户输入密码以访问授权管理功能"""
        def check_password():
            password = password_entry.get().strip()
            if password == "carl_yang":
                password_window.destroy()
                self._manage_license()
            else:
                messagebox.showerror("错误", "密码错误，请重试！")

        password_window = tk.Toplevel(self)
        password_window.title("输入密码")

        tk.Label(password_window, text=LABEL_TEXT).pack(pady=10)
        password_entry = tk.Entry(password_window, show="*")
        password_entry.pack(pady=10)

        tk.Button(password_window, text=BUTTON_TEXT, command=check_password).pack(pady=10)

    def _manage_license(self):
        """授权管理窗口"""
        def generate_license():
            mac_address = mac_entry.get().strip()
            start_date = date_entry.get().strip()
            validity_days = days_entry.get().strip()

            if not mac_address or not start_date or not validity_days.isdigit():
                messagebox.showerror("错误", "请输入有效的授权信息！")
                return

            license_code = encrypt_license_info(mac_address, start_date, int(validity_days))
            if license_code:
                result_text.delete("1.0", tk.END)
                result_text.insert(tk.END, f"生成的授权码:\n{license_code}")
            else:
                messagebox.showerror("错误", "生成授权码失败！")

        def validate_license():
            license_code = license_entry.get("1.0", tk.END).strip()
            if not license_code:
                messagebox.showerror("错误", "请输入授权码！")
                return

            valid, message = decrypt_and_validate_license_code(license_code)
            messagebox.showinfo("验证结果", message)

        license_window = tk.Toplevel(self)
        license_window.title("授权管理")

        tk.Label(license_window, text="MAC 地址:").pack(pady=5)
        mac_entry = tk.Entry(license_window)
        mac_entry.pack(pady=5)

        tk.Label(license_window, text="授权开始日期 (YYYY-MM-DD):").pack(pady=5)
        date_entry = tk.Entry(license_window)
        date_entry.pack(pady=5)

        tk.Label(license_window, text="有效期 (天):").pack(pady=5)
        days_entry = tk.Entry(license_window)
        days_entry.pack(pady=5)

        tk.Button(license_window, text="生成授权码", command=generate_license).pack(pady=10)

        tk.Label(license_window, text="授权码:").pack(pady=5)
        license_entry = tk.Text(license_window, height=5, width=40)
        license_entry.pack(pady=5)

        tk.Button(license_window, text="验证授权码", command=validate_license).pack(pady=10)

        result_text = tk.Text(license_window, height=5, width=40, state="normal")
        result_text.pack(pady=5)
